app.controller("openapiCtr", ["$scope", "$http", "$filter", "$rootScope", "$stateParams", "$modal", "lodash",
    function($scope, $http, $filter, $rootScope, $stateParams, $modal, lodash) {
        $scope.currentUrlPath = "http://10.130.24.237:8096/api/v1";
        $scope.info = {
            apiList: [],
            sltApiItem: "",
            paramsList: [],
            sltParamItem: "",
            tabList: [
                {"name": "输入", "type": "in", "active": true},
                {"name": "返回值", "type": "out", "active": false},
                {"name": "结果对比", "type": "diff", "active": false}
            ],
            paramsData: "",
            jsonData: "",
            testRtnData: "",
            isDiff: false,
            leftObj: "",
            rightObj: "",
            isDefault: false,
            updateJson: true,
            showParamLoading: false
        };    

        getApiData();

        // 获取接口数据
        function getApiData() {
            var url = $scope.currentUrlPath + "/method/getMethods?type=op&isParam=0";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    var apiDataArray = new Array();
                    angular.forEach(result.data, function(api) {
                        api.crtname = api.name;
                        apiDataArray.push(api);
                    });
                    $scope.info.apiList = apiDataArray;
                } else {
                    $rootScope.toasterErrorInfo("获取接口列表数据失败！");
                }
            });
        };

        // 根据接口查询参数数据
        $scope.selectApiFun = function(item) {
            getApiDetailsById(item.id);
        };

        // 根据接口数据id获取接口详情
        function getApiDetailsById(itemId) {
            var url = $scope.currentUrlPath + "/method/getMethods?id="+ itemId +"&type=op&isParam=1";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    var defaultApiItem = {
                        "isDefault": true,
                        "crtname": "默认参数",
                        "params": result.data[0].params[0]
                    };
                    $scope.info.paramsList.push(defaultApiItem);
                    getParamListByRelateId(result.data[0].id);
                } else {
                    $rootScope.toasterErrorInfo("获取接口详细数据错误！");
                }
            });
        };

        // 根据relate查询参数列表
        function getParamListByRelateId(relateId) {
            $scope.info.showParamLoading = true;
            $scope.info.sltParamItem = "";
            var url = $scope.currentUrlPath + "/params/getParam?relateId="+ relateId;
            $http.get(url).success(function(result) {
                $scope.info.showParamLoading = false;
                if(result.code == "0") {
                    angular.forEach(result.data, function(param) {
                        if(param.paramJson) {
                            var paramItem = {
                                "id": param.id,
                                "crtname": param.name,
                                "params": param.paramJson.params
                            };
                            $scope.info.paramsList.push(paramItem);
                        }
                    });
                } else {
                    $rootScope.toasterErrorInfo("获取参数数据失败！");
                }
            });
        };

        // 选择参数
        $scope.selectParamFun = function(item) {
            $scope.info.updateJson = false;
            $scope.info.isDefault = item.isDefault || false;
            $scope.info.paramsData = item;
            $scope.info.jsonData = item.params;
            $scope.info.updateJson = true;
        };

        // 打开modal
        $scope.openModal = function(type) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: getTemplateUrl("matrix/servicegate/tpl/addsgmodal.html"),
                controller: "addParamCtrl",
                keyboard: true,
                backdrop: true,
                resolve: {
                    type: function () {
                        return type;
                    },
                    paramItem: function () {
                        return type != "add" ? $scope.info.sltParamItem : "";
                    }
                }
            });
    
            modalInstance.result.then(function (paramTitle) {
                ajaxFun(type, paramTitle);
            }, function (reason) {
                console.log("关闭modal");
            });
        };

        // 新增/修改
        function ajaxFun(type, paramTitle) {
            var paramItem = {
                "id": type == "add" ? "" : $scope.info.sltParamItem.id,
                "name": paramTitle,
                "paramJson": {
                    "params": $scope.info.jsonData
                },
                "relateId": $scope.info.sltApiItem.id,
                "rtn": {}
            };
            var url = $scope.currentUrlPath + "/params/saveParam";
            $http({
                method: "post",
                url: url,
                data: JSON.stringify(paramItem),
                headers: {"Content-Type": "application/json"}
            }).success(function (result) {
                if(result.code == "0") {
                    if(type == "add") {
                        var newParamItem = {
                            "id": result.data.id,
                            "crtname": paramItem.name,
                            "params": paramItem.paramJson.params
                        };
                        $scope.info.paramsList.push(newParamItem);
                        $rootScope.toasterSuccessInfo("添加成功！");
                    } else {
                        var updateItem = lodash.findWhere($scope.info.paramsList, {id: $scope.info.sltParamItem.id});
                        updateItem.name = paramTitle;
                        updateItem.crtname = paramTitle;
                        updateItem.paramJson = $scope.info.jsonData;
                        $rootScope.toasterSuccessInfo("修改成功！");
                    }
                } else {
                    $rootScope.toasterErrorInfo("操作失败！");
                }
            });
        };

        // 切换tab页
        $scope.tabClick = function(tab) {
            switch(tab.type) {
                case "in":
                    $scope.info.isDiff = false;
                    $scope.info.jsonData = $scope.info.paramsData ? $scope.info.paramsData.params : "";
                    break;
                case "out":
                    $scope.info.isDiff = false;
                    $scope.info.jsonData = $scope.info.testRtnData ? $scope.info.testRtnData : "";
                    break;
                case "diff":
                    $scope.info.isDiff = true;
                    $scope.info.leftObj = $filter("json")($scope.info.paramsData ? $scope.info.paramsData.params : "");
                    $scope.info.rightObj = $filter("json")($scope.info.testRtnData);
                    break;
            }
        }

        // 调试
        $scope.testClick = function() {
            if(!$scope.info.jsonData) {
                $rootScope.toasterWarningInfo("输入数据不能为空！");
                return false;
            }
            var url = "../data/outParam.json";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    $scope.info.testRtnData = result.data;
                    $scope.info.jsonData = result.data;
                    // 设置输入tab选中
                    var outItem = lodash.findWhere($scope.info.tabList, {type: "out"});
                    outItem.active = true;
                    $scope.info.isDiff = false;
                } else {
                    $rootScope.toasterErrorInfo("调试失败！");
                }
            });
        };

    }
]);

app.controller("addParamCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "type", "paramItem", function ($scope, $rootScope, $modalInstance, $http, type, paramItem) {
    $scope.info = {
        title: type == "add" ? "添加参数" : "修改参数",
        paramsTitle: paramItem ? paramItem.crtname : ""
    }

    $scope.createClick = function () {
        if(!$scope.info.paramsTitle) {
            $rootScope.toasterWarningInfo("参数名称不能为空！");
            return false;
        }
        $modalInstance.close($scope.info.paramsTitle);
    };

    $scope.cancelClick = function () {
        $modalInstance.dismiss("cancel");
    };
}]);